import { ProForm, ProFormInstance } from '@/components/Pro';
import { deviceManagerControllerGetDeviceModelList } from '@/services/ess/deviceManager';
import { stationAreaControllerImplUpdateStationArea } from '@/services/ess/stationArea';
import { stationSelfDeviceControllerImplUpdateStationDevice as updateDevice } from '@/services/ess/stationDevice';
import { DATABASE_TYPE_ENUM, fetchDictInfo } from '@/utils';
import { CopyOutlined } from '@ant-design/icons';
import { useIntl } from '@umijs/max';
import { Button, ConfigProvider, Form, Input, message, Select, Space, Tooltip } from 'antd';
import React, { useEffect, useRef, useState } from 'react';
import Styles from '../index.less';

type FieldType = {
  baseInfo: {
    id?: number;
    name?: string;
    model?: string;
    type?: number;
    code?: string;
    areaId?: number;
    voltageLevel?: number;
    voltLevel?: number;
    deviceType?: string | null;
    meterType?: number;
  } | null;
  handleBaseInfo: (res: any) => void;
  fliterTreeData: any[];
};

interface DeviceModelVO {
  deviceId: number;
  deviceModelName: string;
}

interface VoltLevelOption {
  label: string;
  value: string;
}

const App: React.FC<FieldType> = (props) => {
  const { baseInfo, handleBaseInfo } = props;
  const FormRef = useRef<ProFormInstance>();
  const [deviceModelList, setDeviceModelList] = useState<DeviceModelVO[]>([]);
  const [voltLevels, setVoltLevels] = useState<VoltLevelOption[]>([]);
  const [meterTypes, setMeterTypes] = useState<VoltLevelOption[]>([]);
  const [initialValues, setInitialValues] = useState<any>({});
  const intl = useIntl();

  const fetchDeviceModelList = async (deviceType: number) => {
    try {
      const result = await deviceManagerControllerGetDeviceModelList({ deviceType });
      setDeviceModelList(result.data || []);
    } catch (error) {
      console.error(intl.formatMessage({ id: 'siteManage.getDeviceModelFail' }), error);
      setDeviceModelList([]);
    }
  };

  const resetNonDisabledFields = () => {
    FormRef.current?.setFieldsValue(initialValues);
  };

  useEffect(() => {
    if (baseInfo) {
      const voltLevelValue = baseInfo.voltLevel || baseInfo.voltageLevel;
      const initialFormValues = {
        ...baseInfo,
        voltLevel: voltLevelValue ? voltLevelValue.toString() : undefined,
        meterType: baseInfo.meterType ? baseInfo.meterType.toString() : undefined,
      };

      FormRef?.current?.setFieldsValue(initialFormValues);
      setInitialValues(initialFormValues);

      if (baseInfo.type) {
        fetchDeviceModelList(baseInfo.type);
      }
    } else {
      FormRef?.current?.resetFields();
      setInitialValues({});
    }

    fetchDictInfo(DATABASE_TYPE_ENUM.VOLT_LEVEL).then((res) => {
      if (res) {
        const formattedVoltLevels = res.map((item: any) => ({
          label: item.label,
          value: item.value.toString(),
        }));
        formattedVoltLevels.sort((a, b) => {
          return parseInt(a.value) - parseInt(b.value);
        });
        setVoltLevels(formattedVoltLevels);
      }
    });

    fetchDictInfo(DATABASE_TYPE_ENUM.METER_TYPE).then((res) => {
      if (res) {
        const formattedMeterTypes = res.map((item: any) => ({
          label: item.label,
          value: item.value.toString(),
        }));
        setMeterTypes(formattedMeterTypes);

        if (baseInfo?.meterType) {
          const currentValues = FormRef.current?.getFieldsValue();
          FormRef.current?.setFieldsValue({
            ...currentValues,
            meterType: baseInfo.meterType.toString(),
          });
        }
      }
    });
  }, [baseInfo]);

  const isAreaParams = (params: any): params is { area_id: string } => {
    return 'area_id' in params;
  };

  const handleFinish = async (value: any) => {
    if (!baseInfo) {
      message.error(intl.formatMessage({ id: 'siteManage.deviceInfoNExist' }));
      return;
    }

    const { id, ...restBaseInfo } = baseInfo;
    if (id === undefined) {
      message.error(intl.formatMessage({ id: 'siteManage.deviceIdNExist' }));
      return;
    }

    const isArea = baseInfo.deviceType === 'area';
    const params = isArea ? { area_id: String(id) } : { device_id: String(id) };

    const selectedModel = deviceModelList.find((model) => model.deviceId === value.model);
    if (selectedModel) {
      value.model = selectedModel.deviceModelName;
    }

    const body = {
      ...restBaseInfo,
      ...value,
      voltLevel: value.voltLevel ? parseInt(value.voltLevel, 10) : undefined,
      meterType: value.meterType ? parseInt(value.meterType, 10) : undefined,
    };

    try {
      let result;
      if (isAreaParams(params)) {
        result = await stationAreaControllerImplUpdateStationArea(params, body);
      } else {
        result = await updateDevice(params, body);
      }
      if (result.success) {
        message.success(intl.formatMessage({ id: 'siteManage.modifiedSuccess' }));
        console.log('result', result);
        handleBaseInfo({ ...result.data, ...value }); // 更新 baseInfo
        FormRef.current?.setFieldsValue({ ...baseInfo, ...value }); // 更新表单初始值
        setInitialValues({ ...result.data, ...value }); // 保存新的初始值
      }
    } catch (error) {
      console.error(intl.formatMessage({ id: 'siteManage.updateFail' }), error);
      message.error(intl.formatMessage({ id: 'siteManage.modifyFail' }));
    }
  };

  // @ts-ignore
  function copyToClipboard(textToCopy) {
    // navigator clipboard 需要https等安全上下文
    if (navigator.clipboard && window.isSecureContext) {
      // navigator clipboard 向剪贴板写文本
      return navigator.clipboard.writeText(textToCopy);
    } else {
      // 创建text area
      let textArea = document.createElement('textarea');
      textArea.value = textToCopy;
      // 使text area不在viewport，同时设置不可见
      textArea.style.position = 'absolute';
      textArea.style.opacity = '0';
      textArea.style.left = '-999999px';
      textArea.style.top = '-999999px';
      document.body.appendChild(textArea);
      textArea.focus();
      textArea.select();
      return new Promise((resolve, reject) => {
        try {
          const successful = document.execCommand('copy');
          if (successful) {
            // @ts-ignore
            resolve();
          } else {
            reject(new Error('Copy command was unsuccessful'));
          }
        } catch (err) {
          reject(err);
        } finally {
          textArea.remove();
        }
      });
    }
  }

  return (
    <div style={{ maxWidth: '600px', padding: '0 20px 20px ' }}>
      {baseInfo && (
        <div>
          <div className={Styles.rightSubTitle}>
            {intl.formatMessage({ id: 'siteManage.deviceBaseInfo' })}
          </div>
          <ProForm
            formRef={FormRef}
            layout="horizontal"
            grid={true}
            labelCol={{
              span: 8,
            }}
            style={{ marginTop: 20 }}
            submitter={{
              render: (props) => (
                <Space style={{ paddingLeft: 120 }}>
                  <Button type="primary" onClick={() => props.form?.submit()}>
                    {intl.formatMessage({ id: 'siteManage.submit' })}
                  </Button>
                  <Button onClick={resetNonDisabledFields}>
                    {intl.formatMessage({ id: 'siteManage.reset' })}
                  </Button>
                </Space>
              ),
            }}
            onFinish={handleFinish}
            onValuesChange={(changedValues) => {
              if (changedValues.type) {
                fetchDeviceModelList(changedValues.type);
              }
            }}
          >
            {baseInfo.deviceType === 'area' ? (
              <>
                <Form.Item
                  name="areaName"
                  label={intl.formatMessage({ id: 'siteManage.areaName' })}
                  className="ant-col ant-col-18"
                  rules={[
                    {
                      required: true,
                      message: intl.formatMessage({ id: 'siteManage.enterAreaName' }),
                    },
                  ]}
                >
                  <Input />
                </Form.Item>
                <Form.Item
                  name="voltLevel"
                  label={intl.formatMessage({ id: 'siteManage.voltageLevel' })}
                  className="ant-col ant-col-18"
                  rules={[
                    {
                      required: true,
                      message: intl.formatMessage({ id: 'siteManage.selectVoltage' }),
                    },
                  ]}
                >
                  <Select
                    options={voltLevels}
                    onChange={(value, option) => {
                      console.log('Selected value:', value);
                      console.log('Selected option:', option);
                    }}
                  />
                </Form.Item>
                <Form.Item
                  name="id"
                  label={intl.formatMessage({ id: 'siteManage.areaId' })}
                  className="ant-col ant-col-18"
                >
                  <Input
                    disabled
                    addonAfter={
                      <ConfigProvider
                        theme={{
                          components: {
                            Button: {
                              paddingInline: 0,
                            },
                          },
                        }}
                      >
                        <Tooltip title={intl.formatMessage({ id: 'siteManage.copyID' })}>
                          <Button
                            style={{ marginLeft: '-8px' }}
                            type="text"
                            size="small"
                            icon={<CopyOutlined />}
                            onClick={() => {
                              copyToClipboard(baseInfo.id?.toString() || '');
                              message.success(intl.formatMessage({ id: 'siteManage.IDcopied' }));
                            }}
                          ></Button>
                        </Tooltip>
                      </ConfigProvider>
                    }
                  />
                </Form.Item>
              </>
            ) : (
              <>
                <Form.Item
                  name="name"
                  label={intl.formatMessage({ id: 'siteManage.deviceName' })}
                  className="ant-col ant-col-12"
                  rules={[
                    {
                      required: true,
                      message: intl.formatMessage({ id: 'siteManage.enterDeviceName' }),
                    },
                  ]}
                >
                  <Input />
                </Form.Item>
                <Form.Item
                  name="type"
                  label={intl.formatMessage({ id: 'siteManage.deviceType' })}
                  className="ant-col ant-col-12"
                  rules={[
                    {
                      required: true,
                      message: intl.formatMessage({ id: 'siteManage.selectDeviceType' }),
                    },
                  ]}
                >
                  <Select
                    disabled
                    options={[
                      { value: 1, label: intl.formatMessage({ id: 'global.batteryCabinet' }) },
                      { value: 2, label: intl.formatMessage({ id: 'global.batteryBox' }) },
                      { value: 3, label: intl.formatMessage({ id: 'global.pcs' }) },
                      { value: 4, label: intl.formatMessage({ id: 'global.meter' }) },
                      { value: 5, label: intl.formatMessage({ id: 'global.transformer' }) },
                      {
                        value: 6,
                        label: intl.formatMessage({ id: 'global.integratedController' }),
                      },
                      { value: 7, label: intl.formatMessage({ id: 'global.cabinetController' }) },
                      { value: 8, label: intl.formatMessage({ id: 'global.cabinetController' }) },
                      { value: 9, label: intl.formatMessage({ id: 'global.inverter' }) },
                      { value: 10, label: intl.formatMessage({ id: 'global.chargingPile' }) },
                    ]}
                  />
                </Form.Item>
                <Form.Item
                  name="model"
                  label={intl.formatMessage({ id: 'siteManage.deviceModel' })}
                  className="ant-col ant-col-12"
                  rules={[
                    {
                      required: true,
                      message: intl.formatMessage({ id: 'siteManage.selectDeviceModel' }),
                    },
                  ]}
                >
                  <Select
                    options={deviceModelList.map((model: DeviceModelVO) => ({
                      label: model.deviceModelName,
                      value: model.deviceId,
                    }))}
                  />
                </Form.Item>
                {baseInfo.type === 4 && (
                  <>
                    <Form.Item
                      name="voltLevel"
                      label={intl.formatMessage({ id: 'siteManage.voltageLevel' })}
                      className="ant-col ant-col-12"
                      rules={[
                        {
                          required: true,
                          message: intl.formatMessage({ id: 'siteManage.selectVoltage' }),
                        },
                      ]}
                    >
                      <Select options={voltLevels} />
                    </Form.Item>
                    <Form.Item
                      name="meterType"
                      label={intl.formatMessage({ id: 'siteManage.meterType' })}
                      className="ant-col ant-col-12"
                      rules={[
                        {
                          required: true,
                          message: intl.formatMessage({ id: 'siteManage.selectMeterType' }),
                        },
                      ]}
                    >
                      <Select options={meterTypes} />
                    </Form.Item>
                  </>
                )}
                <Form.Item
                  name="code"
                  label={intl.formatMessage({ id: 'siteManage.deviceCode' })}
                  className="ant-col ant-col-12"
                >
                  <Input disabled />
                </Form.Item>
              </>
            )}
          </ProForm>
        </div>
      )}
    </div>
  );
};

export default App;
